package com.softwinner.awbt.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;

import com.softwinner.awbt.R;
import com.softwinner.awbt.activity.MainActivity;
import com.softwinner.awbt.common.BTApplication;
import com.softwinner.awbt.dao.CallLog;
import com.softwinner.awbt.dao.CallLogDao;
import com.softwinner.awbt.listener.CallLogListener;
import com.softwinner.awbt.utils.LOG;

import java.util.ArrayList;
import java.util.List;

/**
 * A fragment representing a list of Items.
 * <p/>
 */
public class CallLogFragment extends BaseFragment implements CallLogListener {

    private final int MSG_SYNC_TIMEOUT = 0xFE01;
    private final int SYNC_MAX_TIME = 40 * 1000;

    private static final int SYNC_CALL_OUT = 1;
    private static final int SYNC_MISS_CALL = 2;
    private static final int SYNC_CALL_IN = 3;

    private static final int CALL_OUT_LOG = 4;
    private static final int CALL_IN_LOG = 5;
    private static final int CALL_MISS_LOG = 6;
    private TabHost mTabHost;
    private TextView mTextView;
    private List<CallLog> mCallInLogs = new ArrayList<>();
    private List<CallLog> mCallOutLogs = new ArrayList<>();
    private List<CallLog> mMissCallLogs = new ArrayList<>();

    private MainActivity mActivity;
    private CallLogAdapter mCallInAdapter;
    private CallLogAdapter mCallOutAdapter;
    private CallLogAdapter mCallMissAdapter;

    private static CallLogListener sCallLogListener;

    private String mCurrentAddress;
    private ProgressDialog mProgressDialog;

    private int mSyncType;

    private boolean isLoadFromDevice;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public CallLogFragment() {
        sCallLogListener = this;
    }

    public static CallLogFragment newInstance() {
        return new CallLogFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_call_logs, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        LOG.d("CallLogFragment  initView");
        mTabHost = (TabHost) view.findViewById(R.id.tabhost);
        mTextView = (TextView) view.findViewById(R.id.sync_tv);

        mTabHost.setup();
        // 如果没有继承TabActivity时，通过该种方法加载启动tabHost
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.call_in)).setIndicator(getString(R
                .string.call_in), getResources().getDrawable(R.drawable.ic_phone_in)).setContent
                (R.id.call_in_lv));
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.call_out)).setIndicator(getString
                (R.string.call_out), getResources().getDrawable(R.drawable.ic_phone_out))
                .setContent(R.id.call_out_lv));
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.call_miss)).setIndicator(getString
                (R.string.call_miss), getResources().getDrawable(R.drawable.ic_phone_missed))
                .setContent(R.id.call_missed_lv));
        ListView callinView = (ListView) view.findViewById(R.id.call_in_lv);
        ListView calloutView = (ListView) view.findViewById(R.id.call_out_lv);
        ListView callmissView = (ListView) view.findViewById(R.id.call_missed_lv);

        mCallInAdapter = new CallLogAdapter(getContext(), mCallInLogs);
        mCallOutAdapter = new CallLogAdapter(getContext(), mCallOutLogs);
        mCallMissAdapter = new CallLogAdapter(getContext(), mMissCallLogs);

        callinView.setAdapter(mCallInAdapter);
        calloutView.setAdapter(mCallOutAdapter);
        callmissView.setAdapter(mCallMissAdapter);

        callinView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                callPhone(mCallInAdapter.getItem(i).getPhonenumber());
            }
        });

        calloutView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                callPhone(mCallOutAdapter.getItem(i).getPhonenumber());
            }
        });

        callmissView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                callPhone(mCallMissAdapter.getItem(i).getPhonenumber());
            }
        });

        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadCallOutLogs();
                mHandler.sendEmptyMessageDelayed(MSG_SYNC_TIMEOUT, SYNC_MAX_TIME);
            }
        });

        if (mCallInLogs.size() > 0) {
            mTextView.setVisibility(View.GONE);
        }

        if (BTApplication.getInstance().getStatus() <= BTApplication.STATUS_DISCONNECTED) {
            mTextView.setVisibility(View.GONE);
        }
    }


    public void callPhone(String number) {
        if (mActivity != null) {
            mActivity.callPhone(number);
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mActivity = (MainActivity) context;
        }
    }

    @Override
    public void onDestroyView() {
        dismissProgressDialog();
        mTabHost.clearAllTabs();
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        mActivity = null;
        sCallLogListener = null;
        mCurrentAddress = null;
        super.onDetach();
    }

    @Override
    public void onCallLog(int type, String name, String number) {
        CallLog callLog = new CallLog(null, name, number, type, BTApplication.getInstance()
                .getCurrentAddress());
        switch (type) {
            case CALL_OUT_LOG:
                if (mCallOutLogs == null) {
                    mCallOutLogs = new ArrayList<>();
                }
                mCallOutLogs.add(callLog);
                break;
            case CALL_MISS_LOG:
                if (mMissCallLogs == null) {
                    mMissCallLogs = new ArrayList<>();
                }
                mMissCallLogs.add(callLog);
                break;
            case CALL_IN_LOG:
                mCallInLogs.add(callLog);
                break;
        }
    }

    @Override
    public void onCallLogDone() {
        switch (mSyncType) {
            case SYNC_CALL_OUT:
                loadCallMissLogs();
                if (isDetach()) {
                    return;
                }
                mTextView.setVisibility(View.GONE);
                mCallOutAdapter.setCallLogs(mCallOutLogs);

                break;
            case SYNC_MISS_CALL:
                loadCallInLogs();
                if (isDetach()) {
                    return;
                }
                mCallMissAdapter.setCallLogs(mMissCallLogs);
                break;
            case SYNC_CALL_IN:
                if (isDetach()) {
                    return;
                }
                mCallInAdapter.setCallLogs(mCallInLogs);
                dismissProgressDialog();
                mHandler.removeMessages(MSG_SYNC_TIMEOUT);
                new Thread() {
                    @Override
                    public void run() {
                        if (isLoadFromDevice) {
                            BTApplication.getInstance().getDaoSession().getCallLogDao()
                                    .insertInTx(mCallInLogs);
                            BTApplication.getInstance().getDaoSession().getCallLogDao()
                                    .insertInTx(mCallOutLogs);
                            BTApplication.getInstance().getDaoSession().getCallLogDao()
                                    .insertInTx(mMissCallLogs);
                        }
                    }
                }.start();
                break;
        }


    }

    @Override
    public void onConnected() {
    }

    private void loadCallOutLogs() {
        showProgressDialog();
        mSyncType = SYNC_CALL_OUT;
        mCallOutLogs = BTApplication.getInstance().getDaoSession().getCallLogDao().queryBuilder()
                .where(CallLogDao.Properties.Address.eq(BTApplication.getInstance()
                        .getCurrentAddress()), CallLogDao.Properties.Calltype.eq(Integer.valueOf
                        (CALL_OUT_LOG))).list();

        if (mCallOutLogs.size() == 0) {
            isLoadFromDevice = true;
            if (mActivity != null) {
                mActivity.syncCallLogs(mSyncType);
            }
        } else {
            isLoadFromDevice = false;
            onCallLogDone();
        }
    }

    private void loadCallMissLogs() {
        mSyncType = SYNC_MISS_CALL;
        mMissCallLogs = BTApplication.getInstance().getDaoSession().getCallLogDao().queryBuilder
                ().where(CallLogDao.Properties.Address.eq(BTApplication.getInstance()
                .getCurrentAddress()), CallLogDao.Properties.Calltype.eq(Integer.valueOf
                (CALL_MISS_LOG))).list();

        if (mMissCallLogs.size() == 0) {
            if (mActivity != null) {
                mActivity.syncCallLogs(mSyncType);
            }
        } else {
            onCallLogDone();
        }
    }

    private void loadCallInLogs() {
        mSyncType = SYNC_CALL_IN;
        mCallInLogs = BTApplication.getInstance().getDaoSession().getCallLogDao().queryBuilder()
                .where(CallLogDao.Properties.Address.eq(BTApplication.getInstance()
                        .getCurrentAddress()), CallLogDao.Properties.Calltype.eq(Integer.valueOf
                        (CALL_IN_LOG))).list();

        if (mCallInLogs.size() == 0) {
            if (mActivity != null) {
                mActivity.syncCallLogs(mSyncType);
            }
        } else {
            onCallLogDone();
        }
    }

    @Override
    public void onDisconnected() {
        dismissProgressDialog();
        mCallInLogs.clear();
        mCallOutLogs.clear();
        mMissCallLogs.clear();

        if (mTabHost != null) {
            mCallInAdapter.notifyDataSetChanged();
            mCallOutAdapter.notifyDataSetChanged();
            mCallMissAdapter.notifyDataSetChanged();

        }
        if (mTextView != null) {
            mTextView.setVisibility(View.GONE);
        }

    }

    @Override
    public void onCurrentAddress(String address) {
        LOG.d("CallLogFragment--onCurrentAddress");
        mCurrentAddress = address;
        loadCallOutLogs();
        if (isDetach()) {
            return;
        }
        mTextView.setVisibility(View.VISIBLE);
    }

    public static CallLogListener getsCallLogListener() {
        return sCallLogListener;
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SYNC_TIMEOUT:
                    dismissProgressDialog();
                    mTextView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    private void showProgressDialog() {
        if (isDetach()) {
            return;
        }
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(getString(R.string.sync_call_logs));
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}
